"use server";
import { PrismaClient } from "@prisma/client";

// 检查 table 中是否存在 column_lable = value 的数据。排除 excludeID
async function checkExist(table, columnLabel, value, excludeID = null) {
  const client = new PrismaClient();
  const where = {
    [columnLabel]: value,
  };

  const record = await client[table].findUnique({
    where,
  });

  return record && (!excludeID || record.id !== excludeID)
    ? { result: "error", message: `${value} 已存在` }
    : { result: "success" };
}

// 增加数据，检查是否存在重复数据
// 检查 checkColumn 是否存在 checkValue，如果存在则返回错误
// data 是要插入的数据，json 格式
async function insert(table, data, columnLabel = null, value = null) {
  const client = new PrismaClient();

  // 如果 columnLabel 和 value 都存在，则检查是否存在重复数据
  if (columnLabel && value) {
    const exist = await checkExist(table, columnLabel, value);
    if (exist.result === "error") {
      return exist;
    }
  }

  const record = await client[table].create({
    data,
  });

  return record
    ? { result: "success", message: "添加成功" }
    : { result: "error", message: "添加失败" };
}

// 删除数据
async function remove(table, columnLabel, value) {
  const client = new PrismaClient();
  const where = {
    [columnLabel]: value,
  };

  const record = await client[table].delete({
    where,
  });

  return record
    ? { result: "success", message: "删除成功" }
    : { result: "error", message: "删除失败" };
}

// 获取所有数据. relation 是关联表, selectColumns 是要选择的字段。例如 ["id", "name"]
async function getAll(table, relation = null, selectColumns = null) {
  const client = new PrismaClient();

  if (relation && selectColumns) {
    // 把 selectColumns 转换成对象格式
    const selectJson = selectColumns.reduce((acc, column) => {
      acc[column] = true;
      return acc;
    }, {});

    // 获取关联表的数据
    const records = await client[table].findMany({
      include: {
        [relation]: {
          select: selectJson,
        },
      },
    });

    return records;
  }

  const records = await client[table].findMany();
  return records;
}

// 根据某个字段的值获取数据
async function getByValue(table, columnLabel, value) {
  const client = new PrismaClient();
  const where = {
    [columnLabel]: value,
  };

  const records = await client[table].findMany({
    where,
  });

  return records;
}

// 更新数据
async function update(table, columnLabel, value, updateData) {
  const client = new PrismaClient();
  const where = {
    [columnLabel]: value,
  };

  const record = await client[table].update({
    where,
    data: updateData,
  });

  return record
    ? { result: "success", message: "更新成功" }
    : { result: "error", message: "更新失败" };
}

// 获取表单 column 对应的所有数据
async function getColumnData(table, column) {
  const client = new PrismaClient();
  const records = await client[table].findMany({
    select: {
      [column]: true,
    },
  });

  if (!records) {
    return [];
  }

  return records;

  // 把 record 对应的值拿出来，返回一个数组
  // return records.map((record) => record[column]);
}

export {
  insert,
  remove,
  getAll,
  getByValue,
  update,
  checkExist,
  getColumnData,
};
